import { to } from 'await-to-js';
import { getToken, removeToken, setToken, getOaTickket, setOaTickket, removeOaTickket } from '@/utils/auth';
import store from '@/store';
import { login as loginApi, logout as logoutApi, } from '@/api/login';
import { defineStore } from 'pinia';
// const oaURL = import.meta.env.VITE_APP_BASE_API
import OARequest from '@/utils/oaRequest';

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken());
  const oaTickket = ref(getOaTickket)
  const nickname = ref('');
  const userId = ref('');
  const tenantId = ref('');
  const avatar = ref('');
  const roles = ref([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref([]); // 用户权限编码集合 → 判断按钮权限
  const name = ref('');
  const heartbeatInterval = ref(null);
  /**
  * 登录
  * @param userInfo
  * @returns
  */
  async function getOaUserData() {
    // const response = await fetch(`https://oa.cntcitc.com.cn/seeyon/main.do?method=login&ticket=${oaTickket.value}&ssoFrom=jgpt&UserAgentFrom=pc`);
    const response = await OARequest({
      url: `/seeyon/main.do?method=login&ticket=${oaTickket.value}&ssoFrom=jgpt&UserAgentFrom=pc`,
      method: 'get',
    });
    const data = await response.json();
    console.log(data,'data')
  }

  const login = async (userInfo) => {
    const [err, res] = await to(loginApi(userInfo));
    if (res) {
      const data = res.data;
      setToken(data.access_token);
      setOaTickket(data.oaTickket);
      token.value = data.access_token;
      oaTickket.value = data.oaTickket;
      getOaUserData()
      return Promise.resolve();
    }
    return Promise.reject(err);
  };
  
  // 获取用户信息
  const getInfo = async () => {
    const [err, res] = await to(getUserInfo());
    if (res) {
      const data = res.data;
      const user = data.user;
      const profile = user.avatar == '' || user.avatar == null ? defAva : user.avatar;

      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = data.roles;
        permissions.value = data.permissions;
      } else {
        roles.value = ['ROLE_DEFAULT'];
      }
      name.value = user.userName;
      nickname.value = user.nickName;
      avatar.value = profile;
      userId.value = user.userId;
      tenantId.value = user.tenantId;
      return Promise.resolve();
    }
    return Promise.reject(err);
  };
  const userData = useCookie('userData')
  const router = useRouter()
  const ability = useAbility()
  // 注销
  const logout = async () => {
    await logoutApi();
    token.value = '';
    roles.value = [];
    permissions.value = [];
    removeToken();
    removeOaTickket();
    clearInterval(heartbeatInterval.value);
    useCookie('accessToken').value = null
    // Remove "userData" from cookie
    userData.value = null
    // Redirect to login page
    await router.push('/login')
    // ℹ️ We had to remove abilities in then block because if we don't nav menu items mutation is visible while redirecting user to login page
    // Remove "userAbilities" from cookie
    useCookie('userAbilityRules').value = null
    // Reset ability to initial ability
    ability.update([])
  };

  const setAvatar = (value) => {
    avatar.value = value;
  };

  return {
    userId,
    tenantId,
    token,
    nickname,
    avatar,
    roles,
    permissions,
    login,
    getInfo,
    logout,
    setAvatar
  };
});

export default useUserStore;

